//
//  LookingDetailsViewController.m
//  Doctor1.0
//
//  Created by mk on 15/11/12.
//  Copyright (c) 2015年 cocoa-mk. All rights reserved.
//

#import "LookingDetailsViewController.h"
#import "Doctor.h"
#import "TeamData.h"
#import "CityOrDepartmentrCell.h"

#import "NewReservationListViewController.h"
#import "TeamStarDetailViewController.h"

@interface LookingDetailsViewController ()
{
    DoctorListData * doctorList;//医生列表
    TeamInfpData * teamData;//团队信息
    NSMutableDictionary * dicExpert;//专家
    NSString * strDisease;//急病详情
    BOOL showMoreDesc;
    
    NSMutableArray * arrayCity1;
    NSInteger selectCity;
    NSInteger selectSubCity;//子城市
    NSString * strCityID;
}

@end

@implementation LookingDetailsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    titleLabel.text = self.strTitle;
    [btnMore setImage:[UIImage imageNamed:@"location_icon.png"] forState:UIControlStateNormal];
    [btnMore setTitle:@"全部" forState:UIControlStateNormal];
    [btnMore setTitleColor:UIColorFromRGB(0x1d,0x89, 0x7c) forState:UIControlStateNormal];
    strCityID = @"-1";
    [self getCity];
    
    doctorList = [[DoctorListData alloc]init];
    teamData = [[TeamInfpData alloc]init];
    teamData.teamID = @"";
    dicExpert = [[NSMutableDictionary alloc]initWithCapacity:0];
    strDisease = @"";
    
    [tableMain becomeRefreshing:NO];
    showMoreDesc = NO;
}

#pragma mark 获取数据
-(void)getCity
{
    NSString * strUrl = [NSString stringWithFormat:@"/city"];
    [[HttpClient manager]GET:strUrl
                  parameters:nil
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         id data = [responseObject objectForKey:requestDataKey];
         if ([data isKindOfClass:[NSArray class]])
         {
             arrayCity1 = [[NSMutableArray alloc]initWithArray:data];
//             if (arrayCity1.count > 0)
//             {
//                 NSMutableDictionary * dic = [arrayCity1 objectAtIndex:0];
//                 NSMutableArray * arr = [dic objectForKey:@"subCity"];
//                 NSMutableDictionary * dicSub = [arr objectAtIndex:0];
//                 NSString * strCity = [NSString stringWithFormat:@"%@",[dicSub objectForKey:@"city"]];
//                 
//                 strCityID = [NSString stringWithFormat:@"%@",[dicSub objectForKey:@"id"]];
//                 [btnMore setTitle:strCity forState:UIControlStateNormal];
//                 [tableCity1 reloadData];
//                 [tableCity2 reloadData];
//             }
             
             NSMutableDictionary * subCity = [[NSMutableDictionary alloc]init];
             NSMutableDictionary * dicState = [[NSMutableDictionary alloc]initWithCapacity:0];
             [dicState setObject:@"-1" forKey:@"id"];
             [dicState setObject:@"全部" forKey:@"state"];
             [dicState setObject:subCity forKey:@"subCity"];
             [arrayCity1 addObject:dicState];
             
             strCityID = @"-1";
             [btnMore setTitle:@"全部" forState:UIControlStateNormal];
             [tableCity1 reloadData];
             [tableCity2 reloadData];
             
         }
    
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         HUDShowRequestError(error.domain, self.view)
     }];
    
}

#pragma mark 团队
-(void)getTeamData
{
    //NSLog(@"===%@",self.strDiseaseHeadUrl);
    teamData.urlPath = [NSString stringWithFormat:@"%@%@",self.strDiseaseHeadUrl,self.strTypeID];
    teamData.strDataKey = @"team";
    [teamData getLoadData:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        //NSLog(@"==%@",responseObject);
        id requestData =[responseObject objectForKey:requestDataKey];
        if ([requestData isKindOfClass:[NSDictionary class]])
        {
            id disease = [requestData objectForKey:@"disease"];
            if (disease && [disease isKindOfClass:[NSDictionary class]])
            {
               strDisease = NullObjToString([disease objectForKey:@"desc"]);
            }
            
            id leader = [requestData objectForKey:@"leader"];
            if (leader && [leader isKindOfClass:[NSDictionary class]])
            {
                [dicExpert addEntriesFromDictionary:leader];
            }
            
            [tableMain reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
        HUDShowRequestError(error.domain, self.view)
    }];
}


//获取医生列表信息
-(void)getDoctorData
{
    [self getTeamData]; //获取团队
    
    if([strCityID isEqualToString:@"-1"])//全部
    {
      doctorList.urlPath = [NSString stringWithFormat:@"%@%@",self.strDoctorUrl,self.strTypeID];
    }else
    {
    doctorList.urlPath = [NSString stringWithFormat:@"%@%@&city=%@",self.strDoctorUrl,self.strTypeID,strCityID];
    }
    
    doctorList.strDataKey = requestDataKey;
    [doctorList loadPageData:^(AFHTTPRequestOperation *operation, id responseObject, BOOL haveNextPage)
     {
         [tableMain reloadData];
         [tableMain refreshFinished];
         tableMain.loadMoreView.state = (haveNextPage?LOADMORENORMAL:LOADMOREFINISHED);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [tableMain refreshFinished];
         tableMain.loadMoreView.state = LOADMORENORMAL;
          HUDShowRequestError(error.domain, self.view)
    }];
}



#pragma mark tableDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == tableMain)
    {
        return doctorList.dataArray.count+1;
    }
    else if (tableView == tableCity1)
    {
        return arrayCity1.count;
        
    }else if (tableView == tableCity2)
    {
        if(arrayCity1.count>0)
        {
            NSMutableDictionary * dic = [arrayCity1 objectAtIndex:selectCity];
            return [[dic objectForKey:@"subCity"] count];
        }
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == tableMain)
    {
        if (indexPath.row == 0)
        {
            if ([teamData.teamID isEqualToString:@""])
            {
                return 0;
            }
            static NSString *CellTableIdentifier = @"LookDetailsTeamCellStr";
            LookDetailsTeamCell *cellLayout = (LookDetailsTeamCell *)[tableView dequeueReusableCellWithIdentifier:CellTableIdentifier];
            if (!cellLayout)
            {
                cellLayout = (LookDetailsTeamCell *)[[[NSBundle mainBundle] loadNibNamed:@"LookDetailsTeamCell" owner:self options:nil] objectAtIndex:0];
                
                cellLayout.labDesc.text = strDisease;
                cellLayout.labTeamName.text = teamData.name;
                [cellLayout fillDataWith:dicExpert showMoreDesc:showMoreDesc];
            }
            //更新UIView的layout过程和Autolayout
            [cellLayout layoutIfNeeded];
            [cellLayout updateConstraintsIfNeeded];
            
            //通过systemLayoutSizeFittingSize返回最低高度
            CGFloat height = [cellLayout.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
            
            return height;
            
        }
        
        static NSString *CellTableIdentifier = @"DoctorTableViewCellStr";
        DoctorTableViewCell *cell = (DoctorTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellTableIdentifier];
        if (!cell)
        {
            cell = (DoctorTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"DoctorTableViewCell" owner:self options:nil] objectAtIndex:0];
        }
        cell.doc = [doctorList.dataArray objectAtIndex:indexPath.row-1];
        //更新UIView的layout过程和Autolayout
        [cell layoutIfNeeded];
        [cell updateConstraintsIfNeeded];
        
        //通过systemLayoutSizeFittingSize返回最低高度
        CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        
        return height;
    }else
         return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == tableMain)
    {
        if (indexPath.row == 0)
        {
            static NSString *CellTableIdentifier = @"LookDetailsTeamCellStr";
            LookDetailsTeamCell *cell = (LookDetailsTeamCell *)[tableView dequeueReusableCellWithIdentifier:CellTableIdentifier];
            if (!cell)
            {
                cell = (LookDetailsTeamCell *)[[[NSBundle mainBundle] loadNibNamed:@"LookDetailsTeamCell" owner:self options:nil] objectAtIndex:0];
            }
            cell.celldelegate = self;
            
            cell.labDesc.text = strDisease;
            cell.labTeamName.text = teamData.name;
            
            [cell fillDataWith:dicExpert showMoreDesc:showMoreDesc];
            return cell;
       
         }
           static NSString *CellTableIdentifier = @"DoctorTableViewCellStr";
            DoctorTableViewCell *cell = (DoctorTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellTableIdentifier];
            if (!cell)
            {
                cell = (DoctorTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"DoctorTableViewCell" owner:self options:nil] objectAtIndex:0];
            }
            cell.delegate = self;
            cell.doc = [doctorList.dataArray objectAtIndex:indexPath.row-1];
            return cell;
    
    }
    else
    {
        static NSString *CellTableIdentifier = @"CityOrDepartmentrCellStr";
        
        CityOrDepartmentrCell *cell = (CityOrDepartmentrCell *)[tableView dequeueReusableCellWithIdentifier:CellTableIdentifier];
        if (!cell)
        {
            cell = (CityOrDepartmentrCell *)[[[NSBundle mainBundle] loadNibNamed:@"CityOrDepartmentrCell" owner:self options:nil] objectAtIndex:0];
        }
        cell.backgroundColor = tableView.backgroundColor;
        
        if (tableView == tableCity1)[cell fillTitleDataWith:[[arrayCity1 objectAtIndex:indexPath.row] objectForKey:@"state"] showLine:NO];
        if (tableView == tableCity2)
        {
            NSMutableDictionary * dic = [arrayCity1 objectAtIndex:selectCity];
            NSMutableArray * arrSub = [dic objectForKey:@"subCity"];
            NSString * strCity = [[arrSub objectAtIndex:indexPath.row] objectForKey:@"city"];
            
            [cell fillTitleDataWith:strCity showLine:YES];
        }
        
        return cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == tableMain)
    {
        return;
    }
    else if (tableView == tableCity1)
    {
        if(indexPath.row == arrayCity1.count-1)//最后一行全部
        {
            strCityID = @"-1";
            [btnMore setTitle:@"全部" forState:UIControlStateNormal];
            [self hideAllView];
            [tableMain becomeRefreshing:YES];
        }
        
        selectCity = indexPath.row;
        [tableCity2 reloadData];
        
    }else if (tableView == tableCity2)
    {
        selectSubCity = indexPath.row;
        NSMutableDictionary * dic = [arrayCity1 objectAtIndex:selectCity];
        NSMutableArray * arrSub = [dic objectForKey:@"subCity"];
        NSString * strCity = [[arrSub objectAtIndex:indexPath.row] objectForKey:@"city"];
        
        strCityID = [[arrSub objectAtIndex:indexPath.row] objectForKey:@"id"];
        [btnMore setTitle:strCity forState:UIControlStateNormal];
        [self hideAllView];
        [tableMain becomeRefreshing:YES];
    }
}



#pragma mark pullDelegate
#pragma -mark delegates
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    [tableMain setCanLoadMore:YES];
    doctorList.requestPage = kLoadMoreStartPage;
    doctorList.strLastId = @"1";
    [self getDoctorData];
}

- (void)pullTableViewDidTriggerLoadMore:(PullTableView*)pullTableView
{
    [tableMain refreshFinished];
    [self getDoctorData];
}


#pragma mark cellDelegate

-(void)makeAnappointmentDoctorWith:(DoctorTableViewCell *)cell
{
    if (![gProjConfig needLogin])
    {
        NSIndexPath * index = [tableMain indexPathForCell:cell];
        NewReservationListViewController * list = [[NewReservationListViewController alloc]initWithNibName:@"NewReservationListViewController" bundle:nil];
        list.doctorData = [doctorList.dataArray objectAtIndex:index.row-1];
       // NSLog(@"==%@",list.doctorData.hpDeptName);
        list.reservationDoctor = YES;
        [self.navigationController pushViewController:list animated:YES];
    }
    
}


#pragma markcell delegate
#pragma mark 查看团队
-(void)clickLookTeamWithCell:(LookDetailsTeamCell *)cell
{
    TeamStarDetailViewController *view = [[TeamStarDetailViewController alloc]init];
    view.Url = teamData.actionUrl;
    view.strTitle = teamData.name;
    
    [self.navigationController pushViewController:view animated:YES];
}

#pragma mark 查看更多疾病
-(void)btnLookMoreDescWithCell:(LookDetailsTeamCell *)cell
{
    showMoreDesc = !showMoreDesc;
    [tableMain reloadData];
}

#pragma mark 选择城市
-(void)rightBarAction:(id)sender
{
    [UIView animateWithDuration:0.1 animations:^
     {
         viewCity.hidden = !viewCity.hidden;
     }];
    
    if(arrayCity1.count == 0)
    {
        [self getCity];
    }
}


-(IBAction)hideAllView
{
    [UIView animateWithDuration:0.1 animations:^{
        viewCity.hidden = YES;
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end







